package com.wechat.page.chat.title;

import com.swak.fx.support.AbstractPage;
import com.swak.fx.support.ui.UITextFlow;
import com.swak.utils.StringUtils;
import com.wechat.dto.ChatDTO;
import com.wechat.enums.ContactType;
import com.wechat.page.chat.popup.ProfilePopup;
import com.wechat.page.comps.TitleComp;

import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.input.MouseEvent;

/**
 * ChatTitleComp.
 * 
 * @author 618lf
 */
public class ChatTitleComp extends TitleComp {

	public ChatTitleComp(AbstractPage parent) {
		super(parent);
	}

	@Override
	public void initializeParts() {
		super.initializeParts();
		this.title.setMaxWidth(200);
	}

	@Override
	public void setupEventHandlers() {
		super.setupEventHandlers();
		this.moreBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
			ProfilePopup.newPopup().setChat(chatProperty().get()).show(this.getWindow());
		});
	}

	@Override
	public void setupValueChangedListeners() {
		super.setupValueChangedListeners();
		this.refreshProperty().addListener((ob, o, n) -> this.onChatChange(this.chatProperty().get()));
		this.chatProperty().addListener((ob, o, n) -> this.onChatChange(n));
	}

	private void onChatChange(ChatDTO chat) {
		this.$runUI(() -> {
			this.moreBtn.setVisible(false);
			this.title.getChildren().clear();
			this.number.setText(StringUtils.EMPTY);
			if (chat != null) {
				this.moreBtn.setVisible(true);
				this.buildTextContent(this.title, chat.getNickName());

				// 聊天室
				if (chat.getType() == ContactType.Chat_Room.getType()) {
					this.number.setText("（" + chat.getContactCount() + "）");
				}
			}
		});
	}

	@Override
	public void ellipsis(UITextFlow flow) {
		flow.ellipsis(21);
	}

	// ================================================================================
	// Properties
	// ================================================================================
	private ObjectProperty<ChatDTO> chatProperty = new SimpleObjectProperty<ChatDTO>();

	public ObjectProperty<ChatDTO> chatProperty() {
		return chatProperty;
	}
}
